package com.yc.web.servlets;

import com.yc.bean.Order;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

@WebServlet("/admin/list.action")
public class ListServlet extends BaseServlet{
    public void findAllOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Order c=super.parseObjectFromRequest(req,Order.class);
        int page=1;
        if (req.getParameter("page")!=null){
            page=Integer.parseInt(req.getParameter("page"));
        }
        int limit=2;
        if (req.getParameter("limit")!=null){
            limit=Integer.parseInt(req.getParameter("limit"));
        }
        int skip=(page-1)*limit;

        String sql = "SELECT so.oid, so.userid, so.tel, so.address, so.ordertime, so.ps, so.orderstatus, so.paymentstatus, SUM(roi.dealprice) AS total_dealprice\n" +
                "FROM ShoeOrder so\n" +
                "LEFT JOIN (\n" +
                "    SELECT oid, SUM(dealprice) AS dealprice\n" +
                "    FROM resorderitem\n" +
                "    GROUP BY oid\n" +
                ") roi ON so.oid = roi.oid\n" +
                "WHERE 1=1";
        String sql1 = "SELECT COUNT(*) AS total FROM (\n" + sql + "\n) AS count_table";

        List<Object> params = new ArrayList<>();
        if (c.getEndTime()==null){
            c.setEndTime(new Date());
        }

        if (c.getStartTime() != null ) {
            sql += " and so.ordertime BETWEEN ? AND ?";
            sql1 += " and so.ordertime BETWEEN ? AND ?";
            params.add(c.getStartTime());
            params.add(c.getEndTime());
        }

        if (c.getOid() != null) {
            sql += " and so.oid = ?";
            sql1 += " and so.oid = ?";
            params.add(c.getOid());
        }

        if (c.getUserid() != null) {
            sql += " and so.userid = ?";
            sql1 += " and so.userid = ?";
            params.add(c.getUserid());
        }

        if (c.getTel() != null && !"".equals(c.getTel())) {
            sql += " and so.tel LIKE ?";
            sql1 += " and so.tel LIKE ?";
            params.add("%" + c.getTel() + "%");
        }

        if (c.getAddress() != null && !"".equals(c.getAddress())) {
            sql += " and so.address LIKE ?";
            sql1 += " and so.address LIKE ?";
            params.add("%" + c.getAddress() + "%");
        }

        if (c.getOrderstatus() != null && !"".equals(c.getOrderstatus())) {
            sql += " and so.orderstatus LIKE ?";
            sql1 += " and so.orderstatus LIKE ?";
            params.add("%" + c.getOrderstatus() + "%");
        }

        if (c.getPaymentstatus() != null && !"".equals(c.getPaymentstatus())) {
            sql += " and so.paymentstatus LIKE ? ";
            sql1 += " and so.paymentstatus LIKE ? ";
            params.add("%" + c.getPaymentstatus() + "%");
        }

        sql += " GROUP BY so.oid, so.userid, so.tel, so.address, so.ordertime, so.ps, so.orderstatus, so.paymentstatus HAVING total_dealprice IS NOT NULL";
        sql1 += " GROUP BY so.oid, so.userid, so.tel, so.address, so.ordertime, so.ps, so.orderstatus, so.paymentstatus HAVING total_dealprice IS NOT NULL";

//        List<Object> result = Collections.singletonList(db.select(sql, params.toArray()));
        List<Map<String, Object>> list=db.select(sql,params.toArray());

// 执行带分页的查询
        params.add(limit);
        params.add(skip);
        List<Map<String, Object>> resultList = db.select(sql + " ORDER BY so.userid LIMIT ? OFFSET ?", params.toArray(new Object[0]));
        Map<String,Object>map=new HashMap<String,Object>();
        int total = list.size(); // 直接使用 list 的大小作为总数，因为这里是无分页的查询
        map.put("code",0);
        map.put("msg","查询用户成功");
        map.put("data",resultList);
        map.put("count",total);
        super.writeObiectJson(map,resp);

    }
    public void sendGood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Order c=super.parseObjectFromRequest(req,Order.class);
        String sql="update ShoeOrder set orderstatus='已发货'where oid=?";
        String sql2="update ShoeOrder set orderstatus='等待处理'where oid=?";
        String sql3="select *from ShoeOrder where orderstatus like'已发货' and oid=?";
        List l=db.select(sql3,c.getOid());
        int r= db.doUpdate(sql,c.getOid());
        Map<String,Object>map=new HashMap<String,Object>();
        if (r>0){
            map.put("code",0);
            map.put("msg","发货成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"发货失败");

            map.put("code",1);
            map.put("msg","等待处理");

        }
        if (l.size()>0) {
            db.doUpdate(sql2,c.getOid());

        }
        super.writeObiectJson(map,resp);

    }
    public void allsend(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        String aid = req.getParameter("oid"); // 假设收到的是字符串 "1,2"
        String[] userIds = aid.split(","); // 拆分字符串，得到用户ID数组 ["1", "2"]

// 构建更新数据库的 SQL 语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE ShoeOrder SET orderstatus='已发货' WHERE oid IN (");

// 生成 SQL 中的占位符
        for (int i = 0; i < userIds.length; i++) {
            sqlBuilder.append("?");
            if (i < userIds.length - 1) {
                sqlBuilder.append(", ");
            }
        }
        sqlBuilder.append(");");

        String sql = sqlBuilder.toString();

// 假设 db.doUpdate 方法可以执行更新操作，参数为 SQL 语句和用户ID数组
        int r = db.doUpdate(sql, (Object[]) userIds);
        Map<String,Object>map=new HashMap<String,Object>();
        System.out.println("SQL: " + sql);
        System.out.println("User IDs: " + Arrays.toString(userIds));
        if (r>0){
            map.put("code",0);
            map.put("msg","批量发货成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"批量发货失败");
            map.put("code",1);
            map.put("msg","批量发货失败");

        }
        super.writeObiectJson(map,resp);}
    public void allDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        String aid = req.getParameter("oid"); // 假设收到的是字符串 "1,2"
        String[] userIds = aid.split(","); // 拆分字符串，得到用户ID数组 ["1", "2"]

// 构建更新数据库的 SQL 语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE ShoeOrder SET orderstatus='等待处理' WHERE oid IN (");

// 生成 SQL 中的占位符
        for (int i = 0; i < userIds.length; i++) {
            sqlBuilder.append("?");
            if (i < userIds.length - 1) {
                sqlBuilder.append(", ");
            }
        }
        sqlBuilder.append(");");

        String sql = sqlBuilder.toString();

// 假设 db.doUpdate 方法可以执行更新操作，参数为 SQL 语句和用户ID数组
        int r = db.doUpdate(sql, (Object[]) userIds);
        Map<String,Object>map=new HashMap<String,Object>();
        System.out.println("SQL: " + sql);
        System.out.println("User IDs: " + Arrays.toString(userIds));
        if (r>0){
            map.put("code",0);
            map.put("msg","批量发货成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"批量发货失败");
            map.put("code",1);
            map.put("msg","批量发货失败");

        }
        super.writeObiectJson(map,resp);}
    public void delOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Order c=super.parseObjectFromRequest(req,Order.class);
        String sql="UPDATE Shoes\n" +
                "JOIN (\n" +
                "    SELECT sid, num\n" +
                "    FROM resorderitem\n" +
                "    WHERE oid = ?\n" +
                ") AS deleted_orders ON shoes.sid = deleted_orders.sid\n" +
                "SET shoes.sstockquantity = shoes.sstockquantity - deleted_orders.num";
        String sql2="DELETE FROM resorderitem\n" +
                "WHERE oid = ?";
        String sql3="select *from resorderitem where oid=?";
        int a=db.doUpdate(sql,c.getOid());
        int b=db.doUpdate(sql2,c.getOid());
        List<Map<String, Object>> l=db.select(sql3,c.getOid());
        Map<String,Object>map=new HashMap<String,Object>();
        if (l.size()==0){
            map.put("code",0);
            map.put("msg","订单完成");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"订单未删除");
            map.put("code",1);
            map.put("msg","订单失败");

        }


    }
}
